<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>部门经理首页</title>
    <link rel="stylesheet" href="../../../css/style.css">

    <!-- 引入 jQuery-->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- 引入 Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <!-- 引入 ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>

    <style>
        /* 复制material_list.html的样式 */
        .submenu { display: none; }
        .menu-item.active > .submenu { display: block; }
        .menu-arrow { transition: transform 0.2s; }
        .menu-item.active > a > .menu-arrow { transform: rotate(90deg); }
        .menu-list > .menu-item.active > a {
            color: #28a745;
            font-weight: bold;
        }
        .table th { background-color: #f8f9fa; }
        .submenu li a.active { color: #28a745; font-weight: bold; transform: translateY(2px); display: inline-block; }
        .search-area { background: #f8f9fa; padding: 10px; border-radius: 8px; margin: 10px 0; width: 100%; }
        .search-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
        .search-item { flex: 0 0 auto; margin-right: 10px; margin-bottom: 5px; }
        .search-item .form-control, .search-item .form-select { width: 120px; height: 31px; font-size: 14px; }
        .search-item .btn { padding: 4px 8px; }
        .search-label { display: block; margin-bottom: 5px; font-size: 14px; color: #555; white-space: nowrap; }
        .table-responsive { overflow-x: auto; margin: 0 -20px; padding: 0 20px; }
        .custom-table { width: 100%; border-collapse: separate; border-spacing: 0; }
        .custom-table th { background: #f8f9fa; color: #495057; font-weight: 600; padding: 12px 15px; border-bottom: 2px solid #dee2e6; white-space: nowrap; }
        .custom-table td { padding: 12px 15px; border-bottom: 1px solid #eee; vertical-align: middle; }
        .action-buttons { display: flex; gap: 8px; }
        .action-buttons .btn { 
            padding: 4px 10px; 
            font-size: 13px;
            min-width: 60px;
            white-space: nowrap;
        }
        .page-title { font-size: 22px; font-weight: 600; margin-bottom: 20px; color: #333; display: flex; align-items: center; gap: 10px; }
        .page-title-icon { font-size: 24px; }
        .ms-auto { margin-left: auto; }
        .add-button { padding: 8px 16px; display: flex; align-items: center; gap: 5px; font-weight: 500; }
        .content-wrapper { padding: 20px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } /* Removed margin */

        /* 新增样式 */
        .row { display: flex; flex-wrap: wrap; margin-right: -15px; margin-left: -15px; }
        .col-md-8, .col-md-4 { position: relative; width: 100%; padding-right: 15px; padding-left: 15px; }
        @media (min-width: 768px) {
            .col-md-8 { flex: 0 0 66.666667%; max-width: 66.666667%; }
            .col-md-4 { flex: 0 0 33.333333%; max-width: 33.333333%; }
        }
        .report-area, .message-list-area { margin-top: 15px; padding: 15px; border: 1px solid #eee; border-radius: 5px; background-color: #f9f9f9; min-height: 300px; }
        .message-card { border: 1px solid #ddd; border-radius: 5px; padding: 15px; margin-bottom: 10px; background-color: #fff; cursor: pointer; transition: box-shadow 0.2s ease-in-out; }
        .message-card:hover { box-shadow: 0 4px 8px rgba(0,0,0,0.1); }
        .message-card h5 { margin-top: 0; margin-bottom: 10px; color: #007bff; }
        .message-card p { margin-bottom: 5px; font-size: 14px; color: #555; }
        .message-card strong { color: #333; }
        .modal-body p { margin-bottom: 8px; }
        .modal-body strong { display: inline-block; width: 120px; color: #333; }

        /* 使主内容区域填充纵向空间 */
        .admin-main {
            display: flex;
            flex-direction: column;
            flex-grow: 1;
        }

        .content-wrapper {
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }

        .content-wrapper .row {
             flex-grow: 1;
        }

        .content-wrapper .row > div {
            display: flex;
            flex-direction: column;
        }

        .report-area, .message-list-area {
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }
        
        /* 修改图表容器样式 */
        .chart-container {
            margin: 15px 0;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            padding: 15px;
        }
        
        .gauge-charts-container {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .gauge-chart {
            flex: 1;
            height: 300px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            padding: 15px;
        }
        
        .bar-chart {
            height: 400px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            padding: 15px;
        }

        .report-area {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
        }

        /* iOS风格模态框样式 */
        .modal.ios-style {
            background: rgba(0, 0, 0, 0.4);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
        }

        .modal.ios-style .modal-dialog {
            max-width: 500px;
            margin: 1.75rem auto;
            display: flex;
            align-items: center;
            min-height: calc(100% - 3.5rem);
        }

        .modal.ios-style .modal-content {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-radius: 20px;
            border: none;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
            overflow: hidden;
        }

        .modal.ios-style .modal-header {
            padding: 20px 20px 10px;
            text-align: center;
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
            position: relative;
        }

        .modal.ios-style .modal-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            width: 100%;
            text-align: center;
        }

        .modal.ios-style .btn-close {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            opacity: 0.5;
            transition: opacity 0.2s;
        }

        .modal.ios-style .btn-close:hover {
            opacity: 1;
        }

        .modal.ios-style .modal-body {
            padding: 20px;
            max-height: 60vh;
            overflow-y: auto;
        }

        .modal.ios-style .form-label {
            font-weight: 500;
            color: #666;
            font-size: 14px;
            margin-bottom: 8px;
        }

        .modal.ios-style .form-control,
        .modal.ios-style .form-select {
            border-radius: 12px;
            border: 1px solid rgba(0, 0, 0, 0.1);
            padding: 10px 15px;
            font-size: 15px;
            transition: all 0.2s;
        }

        .modal.ios-style .form-control:focus,
        .modal.ios-style .form-select:focus {
            border-color: #007AFF;
            box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
        }

        .modal.ios-style .modal-footer {
            padding: 15px 20px 20px;
            border-top: 1px solid rgba(0, 0, 0, 0.1);
            justify-content: center;
            gap: 10px;
        }

        .modal.ios-style .btn {
            border-radius: 12px;
            padding: 10px 25px;
            font-size: 15px;
            font-weight: 500;
            transition: all 0.2s;
        }

        .modal.ios-style .btn-success {
            background: #007AFF;
            border: none;
        }

        .modal.ios-style .btn-success:hover {
            background: #0056CC;
        }

        .modal.ios-style .btn-danger {
            background: #E5E5EA;
            border: none;
            color: #333;
        }

        .modal.ios-style .btn-danger:hover {
            background: #D1D1D6;
        }

        /* 滚动条样式 */
        .modal.ios-style .modal-body::-webkit-scrollbar {
            width: 4px;
        }

        .modal.ios-style .modal-body::-webkit-scrollbar-track {
            background: transparent;
        }

        .modal.ios-style .modal-body::-webkit-scrollbar-thumb {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 2px;
        }

        /* 表单验证样式 */
        .invalid-feedback {
            display: none;
            width: 100%;
            margin-top: 0.25rem;
            font-size: 0.875em;
            color: #dc3545;
        }

        .form-control.is-invalid,
        .form-select.is-invalid {
            border-color: #dc3545;
            padding-right: calc(1.5em + 0.75rem);
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right calc(0.375em + 0.1875rem) center;
            background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
        }

        .form-control.is-invalid:focus {
            border-color: #dc3545;
            box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25);
        }

        .invalid-feedback.show {
            display: block;
        }

        .modal.ios-style .detail-item {
            margin-bottom: 15px;
        }

        .modal.ios-style .detail-item strong {
            color: #666;
            font-size: 14px;
            font-weight: 500;
        }

        .modal.ios-style .detail-item span {
            color: #333;
            font-size: 15px;
        }
    </style>
</head>
<body>
    <div class="admin-layout">
        <!-- 顶部导航栏 -->
        <header class="admin-header">
            <div class="header-left">
                <div class="logo">生产过程管理系统</div>
            </div>
            <div class="header-right">
                <span class="user-info">部门经理</span>
                <span class="user-name">
                    <script>
                        try {
                            const userInfo = localStorage.getItem('userInfo');
                            const user = JSON.parse(userInfo);
                            document.write(user.name || '未登录');
                        } catch (e) {
                            document.write('未登录');
                        }
                    </script>
                </span>
                <button class="logout-btn" onclick="logout()">退出</button>
            </div>
        </header>

        <!-- 左侧菜单 -->
        <aside class="admin-sidebar">
            <ul class="menu-list">
                <li class="menu-item">
                    <a href="manager_home.html">
                        <span class="menu-icon">🏠</span>
                        <span class="menu-title">首页</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">👥</span>
                        <span class="menu-title">人员管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../person/person_list.html">人员列表</a></li>
                        <li><a href="../person/person_edit.html">添加人员</a></li>
                        <li><a href="../person/schedule_edit.html">编辑排班表</a></li>
                        <li><a href="../person/schedule.html">查看排班表</a></li>
                        <li><a href="../person/schedule_statistics.html">班次统计</a></li>
                    </ul>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">📦</span>
                        <span class="menu-title">物料管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../material/material_list.html">物料列表</a></li>
                        <li><a href="*">物料采购统计</a></li>
                    </ul>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">⚙️</span>
                        <span class="menu-title">设备管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../device/device_list.html">设备列表</a></li>
                        <li><a href="*">设备报修报废统计</a></li>
                    </ul>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">📝</span>
                        <span class="menu-title">产品管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../product/product_list.html">产品列表</a></li>
                        <li><a href="../product/editproduct_plan.html">编辑生产计划</a></li>
                        <li><a href="../product/viewproduct_plan.html">查看生产计划</a></li>
                    </ul>
                </li>
                <li class="menu-item">
                    <a href="javascript:void(0)">
                        <span class="menu-icon">🏢</span>
                        <span class="menu-title">供应商管理</span>
                        <span class="menu-arrow"></span>
                    </a>
                    <ul class="submenu">
                        <li><a href="../provider/provider_list.html">供应商列表</a></li>
                    </ul>
                </li>
            </ul>
        </aside>
        <!-- 主内容区域 -->
        <main class="admin-main">
            <div class="content-wrapper">
                <div class="row">
                    <!-- 左侧报表展示区域 -->
                    <div class="col-md-8">
                        <div class="page-title">报表展示</div>
                        <div class="report-area">
                            <div class="dropdown mb-3">
                                <button class="btn btn-primary dropdown-toggle" type="button" id="reportDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                                    选择报表
                                </button>
                                <ul class="dropdown-menu" aria-labelledby="reportDropdown">
                                    <li><a class="dropdown-item" href="#" onclick="showProviderAnalysis(this)">供应商准入与投诉分析</a></li>
                                    <li><a class="dropdown-item" href="#" onclick="showPersonAnalysis(this)">人员数据分析</a></li>
                                    <li><a class="dropdown-item" href="#" onclick="showPlanCompletionAnalysis(this)">生产计划进度统计</a></li>
                                    <li><a class="dropdown-item" href="#" onclick="showRepairAndScrapAnalysis(this)">报修和报废分析</a></li>
                                </ul>
                                <script>
                                document.addEventListener('DOMContentLoaded', function() {
                                    var firstReportItem = document.querySelector('.dropdown-menu .dropdown-item');
                                    if(firstReportItem) {
                                        firstReportItem.classList.add('active');
                                        showProviderAnalysis(firstReportItem);
                                    }
                                });
                                </script>
                            </div>
                            <div id="chartsArea" style="display: none;">
                                <div class="gauge-charts-container">
                                    <div id="approvalRateChart" class="gauge-chart"></div>
                                    <div id="complaintRateChart" class="gauge-chart"></div>
                                </div>
                                <div id="topComplaintsChart" class="bar-chart"></div>
                            </div>
                            <div id="personChartsArea" style="display: none;">
                                <div class="pie-charts-container" style="display: flex; gap: 20px; margin-bottom: 20px; flex-wrap: wrap;">
                                    <div id="departmentChart" class="pie-chart" style="flex: 1; min-width: 320px; height: 400px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); padding: 15px;"></div>
                                    <div id="educationChart" class="pie-chart" style="flex: 1; min-width: 320px; height: 400px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); padding: 15px;"></div>
                                    <div id="titleChart" class="pie-chart" style="flex: 1; min-width: 320px; height: 400px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); padding: 15px;"></div>
                                </div>
                            </div>
                            <div id="repairAndScrapArea" style="display: none;">
                                <div class="gauge-charts-container">
                                    <div id="repairRateChart" class="gauge-chart"></div>
                                    <div id="scrapRateChart" class="gauge-chart"></div>
                                </div>
                                <div id="repairSuccessRateChart" class="bar-chart"></div>
                            </div>
                            <div id="planCompletionArea" style="display: none;">
                                <!-- 整体完成率仪表盘 -->
                                <div class="gauge-charts-container mb-4">
                                    <div id="planCompletionGauge" class="gauge-chart" style="height: 400px;"></div>
                                </div>
                                <!-- 各车间完成率仪表盘组 -->
                                <div id="departmentGauges" class="mb-4" style="background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); padding: 20px;"></div>
                                <!-- Top 5高效员工条形图 -->
                                <div id="topEmployeesChart" class="bar-chart" style="height: 400px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); padding: 20px;"></div>
                            </div>
                        </div>
                    </div>
                    <!-- 右侧消息列表区域 -->
                    <div class="col-md-4">
                        <div class="page-title">消息列表</div>
                        <div class="message-list-area">
                            <!-- 新增下拉列表 -->
                            <div class="search-item mb-2">
                                <label class="search-label">消息类型</label>
                                <select class="form-select form-select-sm" id="messageTypeFilter">
                                    <option value="all">全部消息</option>
                                    <option value="applications">申请消息</option>
                                    <option value="complaints">投诉消息</option>
                                    <option value="repairs">设备报修</option>
                                </select>
                            </div>
                            <!-- 消息卡片容器，设置最大高度和滚动条 -->
                            <div id="message-cards-container" style="overflow-y: auto;"></div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
    
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            // 确保 DOM 加载完成后执行
            var menuItems = document.querySelectorAll('.menu-list .menu-item');

            menuItems.forEach(function (menuItem) {
                const mainLink = menuItem.querySelector(':scope > a'); // 选择直接子链接
                const submenu = menuItem.querySelector(':scope > .submenu'); // 选择直接子菜单

                if (submenu) {
                    // 如果菜单项有子菜单，在主链接上添加点击事件监听器
                    mainLink.addEventListener('click', function (e) {
                        e.preventDefault(); // 阻止子菜单父项的默认链接行为
                        // 切换父菜单项上的 active 类
                        menuItem.classList.toggle('active');
                    });
                } else {
                    // 如果是顶级菜单项且没有子菜单（例如首页）
                    mainLink.addEventListener('click', function (e) {
                        // 从所有菜单项中移除 active 类
                        document.querySelectorAll('.menu-list .menu-item').forEach(function (el) {
                            el.classList.remove('active');
                        });
                        // 为点击的菜单项添加 active 类
                        menuItem.classList.add('active');
                        // 允许默认的链接行为（页面跳转）
                    });
                }
            });

            // 处理子菜单链接的点击事件（允许默认行为）
            document.querySelectorAll('.submenu a').forEach(function(submenuLink) {
             submenuLink.addEventListener('click', function(e) {
                 // 从所有菜单项和子菜单链接中移除 active 类
                 document.querySelectorAll('.menu-list .menu-item').forEach(function (el) {
                     el.classList.remove('active');
                 });
                 document.querySelectorAll('.submenu a').forEach(function(el) {
                     el.classList.remove('active');
                 });

                 // 为父菜单项和点击的子菜单链接添加 active 类
                 const parentMenuItem = submenuLink.closest('.menu-item');
                 if (parentMenuItem) {
                     parentMenuItem.classList.add('active');
                 }
                 submenuLink.classList.add('active');
                 // 允许默认的链接行为（页面跳转）
             });
        });

        // 检查当前页面路径，并在加载时高亮对应的菜单项
        const currentPath = window.location.pathname;
        document.querySelectorAll('.menu-list a').forEach(function (link) {
            // 使用 includes 进行部分路径匹配
            if (link.getAttribute('href') && currentPath.includes(link.getAttribute('href'))) {
                // 首先从所有菜单项和子菜单链接中移除 active 类
                document.querySelectorAll('.menu-list .menu-item').forEach(function (el) {
                    el.classList.remove('active');
                });
                 document.querySelectorAll('.submenu a').forEach(function(el) {
                     el.classList.remove('active');
                 });

                // 为父菜单项添加 active 类
                const parentMenuItem = link.closest('.menu-item');
                if (parentMenuItem) {
                    parentMenuItem.classList.add('active');
                }

                // 如果链接在子菜单中，也为链接本身添加 active 类
                if (link.closest('.submenu')) {
                    link.classList.add('active');
                }
            }
        });

        // 添加消息类型筛选功能
        document.getElementById('messageTypeFilter').addEventListener('change', function () {
            const selectedType = this.value;
            const cards = document.querySelectorAll('#message-cards-container .message-card');
            cards.forEach(card => {
                if (selectedType === 'all') {
                    card.style.display = 'block';
                } else if (selectedType === 'applications') {
                    card.style.display = card.getAttribute('data-application-id') ? 'block' : 'none';
                } else if (selectedType === 'complaints') {
                    card.style.display = card.getAttribute('data-complaint-id') ? 'block' : 'none';
                } else if (selectedType === 'repairs') {
                    card.style.display = card.getAttribute('data-repair-id') ? 'block' : 'none';
                }
            });
        });

    });

    function logout() {
        // 添加确认提示
        if (confirm('确定要退出登录吗？')) {
            // 清除本地存储的登录信息
            localStorage.removeItem('userInfo');
            localStorage.removeItem('token');

            // 跳转到登录页面
            window.location.href = '../../../login.html';
        }
    }

    // 获取并显示未审批的申请和投诉
    async function fetchUnapprovedApplicationsAndComplaints() {
        try {
            // 获取未审批的申请
            const applicationsResponse = await axios.get('http://localhost:8080/api/provider/application/getUnapprovedApplications');
            const applications = applicationsResponse.data;

            // 获取未审核的投诉
            const complaintsResponse = await axios.get('http://localhost:8080/api/provider/complaints/getUnreviewedComplaint');
            const complaints = complaintsResponse.data;

            // 获取未审核的设备报修
            const repairsResponse = await axios.get('http://localhost:8080/api/device/repairs/getUnreviewedRepair');
            const repairs = repairsResponse.data;

            // 获取未审核的设备报废
            const scrapsResponse = await axios.get('http://localhost:8080/api/device/scraps/getUnreviewedScrap');
            const scraps = scrapsResponse.data;

            //获取未审批的产品提交申请
            const product_applicationsResponse = await axios.get('http://localhost:8080/api/production_submissions/getAllApplicationUNPASS');
            const product_applications = product_applicationsResponse.data;

            const container = document.getElementById('message-cards-container');
            container.innerHTML = ''; // 清除现有卡片

            if (applications.length === 0 && complaints.length === 0 && repairs.length === 0 && scraps.length === 0 && product_applications.length === 0) {
                container.innerHTML = '<p>暂无待处理的消息。</p>';
                return;
            }

            // 显示申请消息
            applications.forEach(app => {
                const card = document.createElement('div');
                card.classList.add('message-card');
                card.setAttribute('data-application-id', app.applicationId);
                card.innerHTML = `
                        <h5>供应商申请: ${app.providerName}</h5>
                        <p><strong>工厂地址:</strong> ${app.factoryAddress}</p>
                        <p><strong>工厂类型:</strong> ${app.companyType}</p>
                        <p><strong>申请编号:</strong> ${app.applicationId}</p>
                    `;
                card.addEventListener('click', () => showApplicationDetail(app));
                container.appendChild(card);
            });

            // 显示投诉消息
            complaints.forEach(complaint => {
                const card = document.createElement('div');
                card.classList.add('message-card');
                card.setAttribute('data-complaint-id', complaint.complaintId);
                card.innerHTML = `
                        <h5>供应商投诉: ${complaint.providerName}</h5>
                        <p><strong>问题材料:</strong> ${complaint.defectiveMaterial}</p>
                        <p><strong>投诉描述:</strong> ${complaint.description}</p>
                        <p><strong>投诉编号:</strong> ${complaint.complaintId}</p>
                    `;
                card.addEventListener('click', () => showComplaintDetail(complaint));
                container.appendChild(card);
            });

            // 显示设备报修消息
            repairs.forEach(repair => {
                const card = document.createElement('div');
                card.classList.add('message-card');
                card.setAttribute('data-repair-id', repair.repairId);
                card.innerHTML = `
                        <h5>设备报修: ${repair.deviceName || repair.deviceNumber}</h5>
                        <p><strong>报修描述:</strong> ${repair.repairDesc}</p>
                        <p><strong>申请人:</strong> ${repair.applicantName || repair.applicantJobNumber}</p>
                        <p><strong>报修编号:</strong> ${repair.repairId}</p>
                    `;
                card.addEventListener('click', () => showRepairDetail(repair));
                container.appendChild(card);
            });

            // 显示设备报废消息
            scraps.forEach(scrap => {
                const card = document.createElement('div');
                card.classList.add('message-card');
                card.setAttribute('data-scrap-id', scrap.scrapId);
                card.innerHTML = `
                        <h5>设备报废: ${scrap.deviceName || scrap.deviceNumber}</h5>
                        <p><strong>报废描述:</strong> ${scrap.description}</p>
                        <p><strong>申请人:</strong> ${scrap.applicantName || scrap.applicantJobNumber}</p>
                        <p><strong>报废编号:</strong> ${scrap.scrapId}</p>
                    `;
                card.addEventListener('click', () => showScrapDetail(scrap));
                container.appendChild(card);
            });

            // 显示产品生产消息
            product_applications.forEach(papp =>{
                const card = document.createElement('div');
                card.classList.add('message-card');
                card.setAttribute('data-application-id', papp.submission_id);
                 card.innerHTML = `
                        <h5>产品申请</h5>

                        <p><strong>申请编号:</strong> ${papp.submission_id}</p>
                    `;
                 card.addEventListener('click', () => showProductApplicationDetail(papp));
           container.appendChild(card);
                });

        } catch (error) {
            console.error('获取未审批申请、投诉、设备报修和产品生产时出错:', error);
            const container = document.getElementById('message-cards-container');
            container.innerHTML = '<p>加载消息失败。</p>';
        }
    }

    // 显示产品申请详情的模态框
    // 修改 showProductApplicationDetail 函数
    function showProductApplicationDetail(papp) {

        // 设置基本信息
        document.getElementById('modal-product-submission-id').textContent = papp.submission_id;
        document.getElementById('modal-product-plan-id').textContent = papp.plan_id;
        document.getElementById('modal-product-submitter').textContent = papp.submitter_job_number;
        document.getElementById('modal-product-description').value = papp.description || '';
        document.getElementById('modal-product-review-comment').value = ''; // 清空审核意见

        // 存储当前申请ID，供后续操作使用
        document.getElementById('product-submission-id').value = papp.submission_id;

        // 清空产品明细表格
        const detailTableBody = document.getElementById('modal-product-details-body');
        detailTableBody.innerHTML = '';



        // 根据submission_id获取产品明细
        fetchProductDetails(papp.submission_id)
            .then(details => {
                // 填充产品明细表格
                details.forEach(detail => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${detail.product_code}</td>
                        <td>${detail.product_quantity}</td>
                    `;
                    detailTableBody.appendChild(row);
                });

                // 显示模态框
                const modal = new bootstrap.Modal(document.getElementById('productApplicationDetailModal'));
                modal.show();
            })
            .catch(error => {
                console.error('获取产品明细失败:', error);
                detailTableBody.innerHTML = '<tr><td colspan="2">获取产品明细失败</td></tr>';
                // 即使获取明细失败，也要显示模态框
                const modal = new bootstrap.Modal(document.getElementById('productApplicationDetailModal'));
                modal.show();
            });
    }

    // 获取产品明细数据
    async function fetchProductDetails(submissionId) {
        try {
            const response = await axios.get(`http://localhost:8080/api/production_submission_details/submission/${submissionId}`);
            return response.data;
        } catch (error) {
            console.error('获取产品明细时出错:', error);
            throw error;
        }
    }

    // 批准产品申请
    async function approveProductApplication() {
        const submissionId = document.getElementById('product-submission-id').value;
        const reviewComment = document.getElementById('modal-product-review-comment').value;

        if (!submissionId) {
            alert('无效的申请ID');
            return;
        }

        try {
            // 从模态框中获取 plan_id
            const planId = document.getElementById('modal-product-plan-id').textContent;

            // 构建请求数据 - 确保包含有效的 plan_id
            const requestData = {
                submission_id: parseInt(submissionId),
                plan_id: parseInt(planId), // 确保 plan_id 被正确传递
                is_approved: true,
                comment: reviewComment
            };

            console.log('准备发送批准请求:', requestData);

            const token = localStorage.getItem('token');
            const headers = {
                'Content-Type': 'application/json'
            };

            if (token) {
                headers['Authorization'] = `Bearer ${token}`;
            }

            const response = await axios.put(
                `http://localhost:8080/api/production_submissions/${submissionId}`,
                requestData,
                { headers }
            );
            console.log('服务器响应:', response.data);

            if (response.status === 200 || response.status === 201) {
                alert('产品申请已成功批准！');

                // 关闭模态框
                const modalElement = document.getElementById('productApplicationDetailModal');
                const modal = bootstrap.Modal.getInstance(modalElement);
                if (modal) {
                    modal.hide();
                }

                // 刷新消息列表
                fetchUnapprovedApplicationsAndComplaints();
            } else {
                throw new Error(`服务器返回异常状态码: ${response.status}`);
            }
        } catch (error) {
            console.error('批准申请时发生错误:', error);

            // 更详细的错误信息
            if (error.response) {
                // 服务器返回了错误响应
                console.error('错误响应数据:', error.response.data);
                console.error('错误响应状态:', error.response.status);
                console.error('错误响应头:', error.response.headers);

                if (error.response.status === 401) {
                    alert('身份验证失败，请重新登录');
                    logout(); // 跳转到登录页面
                    return;
                }

                if (error.response.status === 403) {
                    alert('权限不足，无法执行此操作');
                    return;
                }

                if (error.response.status === 404) {
                    alert('申请记录不存在或已被处理');
                    return;
                }

                alert(`服务器错误: ${error.response.data.message || '未知错误'}`);
            } else if (error.request) {
                // 请求已发送，但没有收到响应
                alert('无法连接到服务器，请检查网络连接');
            } else {
                // 请求设置时出错
                alert(`请求错误: ${error.message}`);
            }
        } finally {
            // 恢复按钮状态
            submitButton.disabled = false;
            submitButton.textContent = originalText;
        }
    }
    async function rejectProductApplication() {
        const submissionId = document.getElementById('product-submission-id').value;
        const reviewComment = document.getElementById('modal-product-review-comment').value.trim();

        // 验证审核意见是否填写
        if (!reviewComment) {
            alert('请输入拒绝原因！');
            return;
        }

        try {
            // 1. 插入/更新生产审核记录
            const reviewData = {
                description: reviewComment,
                is_approved: false,
                submission_id_fk: parseInt(submissionId)
            };

            try {
                // 先尝试更新现有记录
                await axios.put(
                    `http://localhost:8080/api/production_reviews/${submissionId}`,
                    reviewData,
                    { headers: { 'Content-Type': 'application/json' } }
                );
            } catch (updateError) {
                // 如果记录不存在，创建新记录
                if (updateError.response?.status === 404) {
                    await axios.post(
                        `http://localhost:8080/api/production_reviews`,
                        reviewData,
                        { headers: { 'Content-Type': 'application/json' } }
                    );
                } else {
                    throw updateError;
                }
            }

            // 2. 删除生产审核记录
            console.log(`删除审核记录: ${submissionId}`);
            await axios.delete(`http://localhost:8080/api/production_reviews/${submissionId}`);
            console.log('审核记录删除成功');

            // 3. 删除对应的生产提交记录
            console.log(`删除主记录: ${submissionId}`);
            await axios.delete(`http://localhost:8080/api/production_submissions/${submissionId}`);
            console.log('主记录删除成功');

            // 4. 删除对应的生产提交明细记录
            try {
                const detailsResponse = await axios.get(
                    `http://localhost:8080/api/production_submission_details/submission/${submissionId}`
                );
                const details = detailsResponse.data;
                console.log(`找到 ${details.length} 条明细记录`);

                await Promise.all(
                    details.map(detail =>
                        axios.delete(`http://localhost:8080/api/production_submission_details/${detail.detail_id}`)
                    )
                );
                console.log('明细记录删除成功');
            } catch (detailError) {
                if (detailError.response?.status === 404) {
                    console.log('明细记录不存在，可能已被级联删除');
                } else {
                    throw detailError;
                }
            }

            alert('产品申请已拒绝并完成相关数据清理！');

            // 5. 关闭模态框并刷新消息列表
            const modalElement = document.getElementById('productApplicationDetailModal');
            const modal = bootstrap.Modal.getInstance(modalElement);
            modal?.hide();

            fetchUnapprovedApplicationsAndComplaints();

        } catch (error) {
            console.error('拒绝产品申请时出错:', error);

            if (error.response) {
                alert(`操作失败 (${error.response.status}): ${error.response.data?.message || '服务器错误'}`);
            } else if (error.request) {
                alert('操作失败: 无法连接到服务器，请检查网络连接');
            } else {
                alert(`操作失败: ${error.message}`);
            }

            if (error.response?.status === 404) {
                alert('申请记录已不存在');
            } else if (error.response?.status === 403) {
                alert('权限不足，无法执行此操作');
            } else if (error.response?.status === 500) {
                if (error.message.includes('foreign key constraint fails')) {
                    alert('操作失败: 数据关联冲突，请刷新页面后重试');
                } else if (error.message.includes('Duplicate entry')) {
                    alert('操作失败: 数据冲突，请刷新页面后重试');
                } else {
                    alert('服务器内部错误，请稍后再试');
                }
            }
        }
    }



    // 显示申请详情的模态框
    function showApplicationDetail(application) {
        // 设置申请详情信息
        document.getElementById('modal-application-id').textContent = application.applicationId;
        document.getElementById('modal-provider-name').textContent = application.providerName;
        document.getElementById('modal-factory-address').textContent = application.factoryAddress;
        document.getElementById('modal-manager-name').textContent = application.managerName;
        document.getElementById('modal-manager-phone').textContent = application.managerPhone;
        document.getElementById('modal-company-type').textContent = application.companyType;
        document.getElementById('modal-registered-capital').textContent = application.registeredCapital;
        document.getElementById('modal-employee-count').textContent = application.employeeCount;
        document.getElementById('modal-established-year').textContent = application.establishedYear;
        document.getElementById('modal-profile').textContent = application.profile;
        document.getElementById('modal-applicant-job-number').textContent = application.applicantJobNumber;

        // 重置表单
        document.getElementById('approvalStatus').value = '';
        document.getElementById('description').value = '';
        document.getElementById('initialRating').value = '';

        // 设置提交审批意见按钮的点击处理程序
        const submitReviewBtn = document.getElementById('submit-review-btn');
        const tempHoldBtn = document.getElementById('temp-hold-btn');

        // 移除之前的事件监听器以避免重复
        submitReviewBtn.removeEventListener('click', submitReview);
        tempHoldBtn.removeEventListener('click', tempHold);

        submitReviewBtn.addEventListener('click', () => submitReview(application.applicationId));
        tempHoldBtn.addEventListener('click', () => tempHold());

        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('applicationDetailModal'));
        modal.show();
    }

    // 提交审批意见
    async function submitReview(applicationId) {
        // 首先进行表单验证
        if (!validateApplicationReviewForm()) {
            return; // 如果验证失败，直接返回
        }

        try {
            const approvalStatus = document.getElementById('approvalStatus').value;
            const description = document.getElementById('description').value.trim();
            const initialRating = document.getElementById('initialRating').value;
            
            // 验证是否选择了处理意见
            if (!approvalStatus) {
                showError(document.getElementById('approvalStatus'), '请选择处理意见');
                return;
            }

            // 验证审核意见
            if (!description) {
                showError(document.getElementById('description'), '请输入审核意见');
                return;
            }

            // 验证初始评分
            const ratingValue = parseInt(initialRating);
            if (isNaN(ratingValue) || ratingValue < 0 || ratingValue > 5 || !Number.isInteger(ratingValue)) {
                showError(document.getElementById('initialRating'), '请输入0-5之间的整数');
                return;
            }

            const isApproved = approvalStatus === 'true';
            
            const reviewData = {
                applicationId: applicationId,
                approved: isApproved,
                description: description,
                initialRating: ratingValue
            };

            const response = await axios.put('http://localhost:8080/api/provider/application/review', reviewData, {
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            console.log('审批意见提交成功:', response.data);
            alert('审批意见已提交！');

            // 关闭模态框
            const modalElement = document.getElementById('applicationDetailModal');
            const modal = bootstrap.Modal.getInstance(modalElement);
            if (modal) {
                modal.hide();
            }

            // 刷新消息列表
            fetchUnapprovedApplicationsAndComplaints();

        } catch (error) {
            console.error('提交审批意见时出错:', error);
            alert('提交审批意见失败！');
        }
    }

    // 暂不处理
    function tempHold() {
        // 关闭模态框
        const modalElement = document.getElementById('applicationDetailModal');
        const modal = bootstrap.Modal.getInstance(modalElement);
        if (modal) {
            modal.hide();
        }
    }

    // 验证报修审核表单
    function validateRepairReviewForm() {
        const approvalStatus = document.getElementById('repairApprovalStatus').value;
        const description = document.getElementById('repairReviewDescription').value.trim();

        // 验证是否选择了处理意见
        if (!approvalStatus) {
            showError(document.getElementById('repairApprovalStatus'), '请选择处理意见');
            return false;
        }

        // 验证审核意见
        if (!description) {
            showError(document.getElementById('repairReviewDescription'), '请输入审核意见');
            return false;
        }

        return true;
    }

    // 暂不处理报修
    function tempHoldRepair() {
        const modalElement = document.getElementById('repairReviewModal');
        const modal = bootstrap.Modal.getInstance(modalElement);
        if (modal) {
            modal.hide();
        }
    }

    // 已移动到底部，使用更健壮的实现

    // 验证报废审核表单
    function validateScrapReviewForm() {
        const approvalStatus = document.getElementById('scrapApprovalStatus').value;
        const description = document.getElementById('scrapReviewDescription').value.trim();

        // 验证是否选择了处理意见
        if (!approvalStatus) {
            showError(document.getElementById('scrapApprovalStatus'), '请选择处理意见');
            return false;
        }

        // 验证审核意见
        if (!description) {
            showError(document.getElementById('scrapReviewDescription'), '请输入审核意见');
            return false;
        }

        return true;
    }

    // 提交设备报废审核意见
    function submitScrapReview(scrapId) {
        // 首先进行表单验证
        if (!validateScrapReviewForm()) {
            return; // 如果验证失败，直接返回
        }

        const approvalStatus = document.getElementById('scrapApprovalStatus').value;
        const description = document.getElementById('scrapReviewDescription').value.trim();
        const isApproved = approvalStatus === 'true';

        const reviewData = {
            scrapId: scrapId,
            isApproved: isApproved,
            description: description
        };

        axios.put('http://localhost:8080/api/device/scraps/review', reviewData, {
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            console.log('报废审核意见提交成功:', response.data);
            alert('报废审核意见已提交！');

            const modalElement = document.getElementById('scrapReviewModal');
            const modal = bootstrap.Modal.getInstance(modalElement);
            if (modal) {
                modal.hide();
            }

            // 刷新消息列表
            fetchUnapprovedApplicationsAndComplaints();
        })
        .catch(error => {
            console.error('提交报废审核意见时出错:', error);
            alert('提交报废审核意见失败！');
        });
    }

    // 暂不处理报废
    function tempHoldScrap() {
        const modalElement = document.getElementById('scrapReviewModal');
        const modal = bootstrap.Modal.getInstance(modalElement);
        if (modal) {
            modal.hide();
        }
    }

    // 显示投诉详情的模态框
    function showComplaintDetail(complaint) {
        document.getElementById('modal-complaint-id').textContent = complaint.complaintId;
        document.getElementById('modal-complaint-provider-name').textContent = complaint.providerName;
        document.getElementById('modal-complaint-material').textContent = complaint.defectiveMaterial;
        document.getElementById('modal-complaint-description').textContent = complaint.description;
        document.getElementById('modal-complaint-job-number').textContent = complaint.complainantJobNumber;

        // 重置表单
        document.getElementById('complaintApprovalStatus').value = '';
        document.getElementById('complaintReviewDescription').value = '';
        document.getElementById('ratingDeduction').value = '';

        // 设置提交审核意见按钮的点击处理程序
        const submitReviewBtn = document.getElementById('submitComplaintReviewBtn');
        const tempHoldBtn = document.getElementById('complaintTempHoldBtn');

        // 移除之前的事件监听器以避免重复
        submitReviewBtn.removeEventListener('click', submitComplaintReview);
        tempHoldBtn.removeEventListener('click', tempHoldComplaint);

        submitReviewBtn.addEventListener('click', () => submitComplaintReview(complaint.complaintId));
        tempHoldBtn.addEventListener('click', () => tempHoldComplaint());

        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('complaintReviewModal'));
        modal.show();
    }

    // 提交投诉审核意见
    async function submitComplaintReview(complaintId) {
        // 首先进行表单验证
        if (!validateComplaintReviewForm()) {
            return; // 如果验证失败，直接返回
        }

        try {
            const approvalStatus = document.getElementById('complaintApprovalStatus').value;
            const description = document.getElementById('complaintReviewDescription').value.trim();
            const ratingDeduction = document.getElementById('ratingDeduction').value;
            
            // 验证是否选择了处理意见
            if (!approvalStatus) {
                showError(document.getElementById('complaintApprovalStatus'), '请选择处理意见');
                return;
            }

            // 验证审核意见
            if (!description) {
                showError(document.getElementById('complaintReviewDescription'), '请输入审核意见');
                return;
            }

            // 验证评级扣分
            const deductionValue = parseInt(ratingDeduction);
            if (isNaN(deductionValue) || deductionValue < 0 || deductionValue > 5 || !Number.isInteger(deductionValue)) {
                showError(document.getElementById('ratingDeduction'), '请输入0-5之间的整数');
                return;
            }

            const isApproved = approvalStatus === 'true';

            const reviewData = {
                complaintId: complaintId,
                approved: isApproved,
                description: description,
                ratingDeduction: deductionValue
            };

            const response = await axios.put('http://localhost:8080/api/provider/complaints/review', reviewData, {
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            console.log('投诉审核意见提交成功:', response.data);
            alert('投诉审核意见已提交！');

            const modalElement = document.getElementById('complaintReviewModal');
            const modal = bootstrap.Modal.getInstance(modalElement);
            if (modal) {
                modal.hide();
            }

            fetchUnapprovedApplicationsAndComplaints();

        } catch (error) {
            console.error('提交投诉审核意见时出错:', error);
            alert('提交投诉审核意见失败！');
        }
    }

    // 暂不处理投诉
    function tempHoldComplaint() {
        const modalElement = document.getElementById('complaintReviewModal');
        const modal = bootstrap.Modal.getInstance(modalElement);
        if (modal) {
            modal.hide();
        }
    }

    // 页面加载时获取申请和投诉
    document.addEventListener('DOMContentLoaded', fetchUnapprovedApplicationsAndComplaints);

    // 动态设置消息卡片容器的高度
    function setMessageCardsContainerHeight() {
        const messageListArea = document.querySelector('.message-list-area');
        const cardsContainer = document.getElementById('message-cards-container');
        if (messageListArea && cardsContainer) {
            // 获取消息列表区域的高度
            const listAreaHeight = messageListArea.offsetHeight;
            // 设置卡片容器高度为消息列表区域高度的 80%
            cardsContainer.style.maxHeight = `${listAreaHeight * 0.8}px`;
        }
    }

    // 在页面加载时设置高度
    document.addEventListener('DOMContentLoaded', setMessageCardsContainerHeight);

    // 在窗口大小变化时重新设置高度
    window.addEventListener('resize', setMessageCardsContainerHeight);

    // 修改显示供应商分析报表函数
    async function showProviderAnalysis(element) {
        try {
            // 更新按钮文本
            document.getElementById('reportDropdown').textContent = element.textContent;
            
            // 获取所有申请和投诉数据
            const applicationsResponse = await axios.get('http://localhost:8080/api/provider/application/getApplications');
            const complaintsResponse = await axios.get('http://localhost:8080/api/provider/complaints/getComplaint');
            
            const applications = applicationsResponse.data;
            const complaints = complaintsResponse.data;

            // 显示图表区域
            document.getElementById('chartsArea').style.display = 'block';

            // 计算审批通过率
            const approvedApplications = applications.filter(app => app.approved && app.status).length;
            const totalReviewedApplications = applications.filter(app => app.status).length;
            const approvalRate = totalReviewedApplications > 0 ? (approvedApplications / totalReviewedApplications * 100).toFixed(2) : 0;

            // 计算投诉通过率
            const approvedComplaints = complaints.filter(comp => comp.approved && comp.status).length;
            const totalReviewedComplaints = complaints.filter(comp => comp.status).length;
            const complaintRate = totalReviewedComplaints > 0 ? (approvedComplaints / totalReviewedComplaints * 100).toFixed(2) : 0;

            // 统计供应商投诉数量
            const providerComplaints = {};
            complaints.forEach(complaint => {
                providerComplaints[complaint.providerName] = (providerComplaints[complaint.providerName] || 0) + 1;
            });

            // 获取投诉最多的前5个供应商
            const topProviders = Object.entries(providerComplaints)
                .sort(([,a], [,b]) => b - a)
                .slice(0, 5);

            // 渲染审批通过率图表
            renderApprovalRateChart(approvalRate);
            // 渲染投诉通过率图表
            renderComplaintRateChart(complaintRate);
            // 渲染Top5投诉供应商图表
            renderTopComplaintsChart(topProviders);

        } catch (error) {
            console.error('获取数据失败:', error);
            alert('获取数据失败，请稍后重试');
        }
    }

    // 修改渲染审批通过率图表函数
    function renderApprovalRateChart(approvalRate) {
        const chart = echarts.init(document.getElementById('approvalRateChart'));
        const option = {
            title: {
                text: '供应商申请审批通过率',
                left: 'center',
                top: '5%',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'normal'
                }
            },
            tooltip: {
                formatter: '{a} <br/>{b} : {c}%'
            },
            series: [{
                name: '审批通过率',
                type: 'gauge',
                startAngle: 180,
                endAngle: 0,
                min: 0,
                max: 100,
                splitNumber: 10,
                radius: '80%',
                center: ['50%', '70%'],
                itemStyle: {
                    color: '#58D9F9',
                    shadowColor: 'rgba(0,138,255,0.45)',
                    shadowBlur: 10,
                    shadowOffsetX: 2,
                    shadowOffsetY: 2
                },
                progress: {
                    show: true,
                    roundCap: true,
                    width: 18
                },
                pointer: {
                    show: false
                },
                axisLine: {
                    roundCap: true,
                    lineStyle: {
                        width: 18
                    }
                },
                axisTick: {
                    distance: -23,
                    splitNumber: 5,
                    length: 8,
                    lineStyle: {
                        width: 1,
                        color: '#999'
                    }
                },
                splitLine: {
                    distance: -23,
                    length: 12,
                    lineStyle: {
                        width: 2,
                        color: '#999'
                    }
                },
                axisLabel: {
                    distance: -25,
                    color: '#999',
                    fontSize: 12,
                    formatter: function(value) {
                        if (value === 0 || value === 100) {
                            return '';
                        }
                        return value;
                    }
                },
                title: {
                    offsetCenter: [0, '-15%'],
                    fontSize: 14
                },
                detail: {
                    backgroundColor: 'transparent',
                    borderWidth: 0,
                    width: 60,
                    height: 40,
                    offsetCenter: [0, '30%'],
                    valueAnimation: true,
                    formatter: '{value}%',
                    color: '#58D9F9',
                    fontSize: 20,
                    fontWeight: 'bold'
                },
                data: [{
                    value: approvalRate,
                    name: '通过率'
                }]
            }]
        };
        chart.setOption(option);
    }

    // 修改渲染投诉通过率图表函数
    function renderComplaintRateChart(complaintRate) {
        const chart = echarts.init(document.getElementById('complaintRateChart'));
        const option = {
            title: {
                text: '供应商投诉通过率',
                left: 'center',
                top: '5%',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'normal'
                }
            },
            tooltip: {
                formatter: '{a} <br/>{b} : {c}%'
            },
            series: [{
                name: '投诉通过率',
                type: 'gauge',
                startAngle: 180,
                endAngle: 0,
                min: 0,
                max: 100,
                splitNumber: 10,
                radius: '80%',
                center: ['50%', '70%'],
                itemStyle: {
                    color: '#FF6E76',
                    shadowColor: 'rgba(255,110,118,0.45)',
                    shadowBlur: 10,
                    shadowOffsetX: 2,
                    shadowOffsetY: 2
                },
                progress: {
                    show: true,
                    roundCap: true,
                    width: 18
                },
                pointer: {
                    show: false
                },
                axisLine: {
                    roundCap: true,
                    lineStyle: {
                        width: 18
                    }
                },
                axisTick: {
                    distance: -23,
                    splitNumber: 5,
                    length: 8,
                    lineStyle: {
                        width: 1,
                        color: '#999'
                    }
                },
                splitLine: {
                    distance: -23,
                    length: 12,
                    lineStyle: {
                        width: 2,
                        color: '#999'
                    }
                },
                axisLabel: {
                    distance: -25,
                    color: '#999',
                    fontSize: 12,
                    formatter: function(value) {
                        if (value === 0 || value === 100) {
                            return '';
                        }
                        return value;
                    }
                },
                title: {
                    offsetCenter: [0, '-15%'],
                    fontSize: 14
                },
                detail: {
                    backgroundColor: 'transparent',
                    borderWidth: 0,
                    width: 60,
                    height: 40,
                    offsetCenter: [0, '30%'],
                    valueAnimation: true,
                    formatter: '{value}%',
                    color: '#FF6E76',
                    fontSize: 20,
                    fontWeight: 'bold'
                },
                data: [{
                    value: complaintRate,
                    name: '通过率'
                }]
            }]
        };
        chart.setOption(option);
    }

    // 修改渲染Top5投诉供应商图表函数
    function renderTopComplaintsChart(topProviders) {
        const chart = echarts.init(document.getElementById('topComplaintsChart'));
        const option = {
            title: {
                text: '投诉最多的前5个供应商',
                left: 'center',
                top: 20,
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'normal'
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                top: '15%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: topProviders.map(([name]) => name),
                axisLabel: {
                    interval: 0,
                    rotate: 30,
                    fontSize: 12,
                    color: '#666'
                },
                axisTick: {
                    alignWithLabel: true
                }
            },
            yAxis: {
                type: 'value',
                name: '投诉数量',
                nameTextStyle: {
                    color: '#666'
                },
                splitLine: {
                    lineStyle: {
                        type: 'dashed'
                    }
                }
            },
            series: [{
                name: '投诉数量',
                data: topProviders.map(([, count]) => ({
                    value: count,
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: '#83bff6' },
                            { offset: 0.5, color: '#5470C6' },
                            { offset: 1, color: '#2f4999' }
                        ])
                    }
                })),
                type: 'bar',
                barWidth: '60%',
                showBackground: true,
                backgroundStyle: {
                    color: 'rgba(180, 180, 180, 0.1)'
                }
            }]
        };
        chart.setOption(option);
    }

    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', function() {
        const charts = ['approvalRateChart', 'complaintRateChart', 'topComplaintsChart']
            .map(id => echarts.getInstanceByDom(document.getElementById(id)))
            .filter(chart => chart);
        
        charts.forEach(chart => chart.resize());
    });

    // 添加表单验证函数
    function validateApplicationReviewForm() {
        let isValid = true;
        
        // 验证处理意见
        const approvalStatus = document.getElementById('approvalStatus');
        if (!approvalStatus.value) {
            showError(approvalStatus, '请选择处理意见');
            isValid = false;
        } else {
            clearError(approvalStatus);
        }
        
        // 验证审核意见
        const description = document.getElementById('description');
        if (!description.value.trim()) {
            showError(description, '请输入审核意见');
            isValid = false;
        } else {
            clearError(description);
        }
        
        // 验证初始评分
        const initialRating = document.getElementById('initialRating');
        const ratingValue = parseInt(initialRating.value);
        if (isNaN(ratingValue) || ratingValue < 0 || ratingValue > 5 || !Number.isInteger(ratingValue)) {
            showError(initialRating, '请输入0-5之间的整数');
            isValid = false;
        } else {
            clearError(initialRating);
        }
        
        return isValid;
    }

    function validateComplaintReviewForm() {
        let isValid = true;
        
        // 验证处理意见
        const approvalStatus = document.getElementById('complaintApprovalStatus');
        if (!approvalStatus.value) {
            showError(approvalStatus, '请选择处理意见');
            isValid = false;
        } else {
            clearError(approvalStatus);
        }
        
        // 验证审核意见
        const description = document.getElementById('complaintReviewDescription');
        if (!description.value.trim()) {
            showError(description, '请输入审核意见');
            isValid = false;
        } else {
            clearError(description);
        }
        
        // 验证评级扣分
        const ratingDeduction = document.getElementById('ratingDeduction');
        const deductionValue = parseInt(ratingDeduction.value);
        if (isNaN(deductionValue) || deductionValue < 0 || deductionValue > 5 || !Number.isInteger(deductionValue)) {
            showError(ratingDeduction, '请输入0-5之间的整数');
            isValid = false;
        } else {
            clearError(ratingDeduction);
        }
        
        return isValid;
    }

    function showError(element, message) {
        element.classList.add('is-invalid');
        let feedback = element.nextElementSibling;
        if (!feedback || !feedback.classList.contains('invalid-feedback')) {
            feedback = document.createElement('div');
            feedback.className = 'invalid-feedback';
            element.parentNode.insertBefore(feedback, element.nextSibling);
        }
        feedback.textContent = message;
        feedback.classList.add('show');
    }

    function clearError(element) {
        element.classList.remove('is-invalid');
        const feedback = element.nextElementSibling;
        if (feedback && feedback.classList.contains('invalid-feedback')) {
            feedback.classList.remove('show');
        }
    }

    // 移除之前的事件监听器绑定，因为我们已经在函数内部进行验证
    const submitReviewBtn = document.getElementById('submit-review-btn');
    const submitComplaintReviewBtn = document.getElementById('submitComplaintReviewBtn');
    
    if (submitReviewBtn) {
        submitReviewBtn.removeEventListener('click', function() {
            if (validateApplicationReviewForm()) {
                submitApplicationReview();
            }
        });
    }
    
    if (submitComplaintReviewBtn) {
        submitComplaintReviewBtn.removeEventListener('click', function() {
            if (validateComplaintReviewForm()) {
                submitComplaintReview();
            }
        });
    }

    // 为输入框添加实时验证
    document.getElementById('initialRating').addEventListener('input', function() {
        const value = this.value;
        if (value !== '') {
            const numValue = parseInt(value);
            if (isNaN(numValue) || numValue < 0 || numValue > 5 || !Number.isInteger(numValue)) {
                showError(this, '请输入0-5之间的整数');
            } else {
                clearError(this);
            }
        }
    });

    document.getElementById('ratingDeduction').addEventListener('input', function() {
        const value = this.value;
        if (value !== '') {
            const numValue = parseInt(value);
            if (isNaN(numValue) || numValue < 0 || numValue > 5 || !Number.isInteger(numValue)) {
                showError(this, '请输入0-5之间的整数');
            } else {
                clearError(this);
            }
        }
    });

    // 显示人员数据分析
    async function showPersonAnalysis(element) {
        try {
            // 更新按钮文本
            document.getElementById('reportDropdown').textContent = element.textContent;
            
            // 隐藏供应商分析图表，显示人员分析图表
            document.getElementById('chartsArea').style.display = 'none';
            document.getElementById('personChartsArea').style.display = 'block';

            // 获取人员统计数据
            const [departmentData, educationData, titleData] = await Promise.all([
                axios.get('http://localhost:8080/api/statistics/department'),
                axios.get('http://localhost:8080/api/statistics/education'),
                axios.get('http://localhost:8080/api/statistics/title')
            ]);

            // // 输出后端返回的数据
            // console.log('车间分布数据:', departmentData.data);
            // console.log('学历分布数据:', educationData.data);
            // console.log('职称分布数据:', titleData.data);

            // 渲染车间分布饼图
            renderDepartmentChart(departmentData.data);
            // 渲染学历分布饼图
            renderEducationChart(educationData.data);
            // 渲染职称分布饼图
            renderTitleChart(titleData.data);

        } catch (error) {
            console.error('获取人员统计数据失败:', error);
            alert('获取人员统计数据失败，请稍后重试');
        }
    }

    // 渲染车间分布饼图
    function renderDepartmentChart(data) {
        const chart = echarts.init(document.getElementById('departmentChart'));
        const option = {
            title: {
                text: '车间人员分布',
                left: 'center',
                top: 20,
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'normal'
                }
            },
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c}人 ({d}%)'
            },
            legend: {
                orient: 'horizontal',
                left: 'center',
                bottom: 0,
                type: 'scroll',
                formatter: function(name) {
                    return name.length > 8 ? name.substring(0, 8) + '...' : name;
                }
            },
            series: [{
                name: '车间分布',
                type: 'pie',
                radius: ['45%', '70%'],
                center: ['50%', '45%'],
                avoidLabelOverlap: true,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: true,
                    position: 'outside',
                    formatter: '{b}：{d}%',
                    fontSize: 12
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 14,
                        fontWeight: 'bold'
                    }
                },
                data: data.map(item => ({
                    name: item.name || '未分配',
                    value: item.value || 0
                }))
            }]
        };
        chart.setOption(option);
    }

    // 渲染学历分布饼图
    function renderEducationChart(data) {
        const chart = echarts.init(document.getElementById('educationChart'));
        const option = {
            title: {
                text: '学历分布',
                left: 'center',
                top: 20,
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'normal'
                }
            },
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c}人 ({d}%)'
            },
            legend: {
                orient: 'horizontal',
                left: 'center',
                bottom: 0,
                type: 'scroll',
                formatter: function(name) {
                    return name.length > 8 ? name.substring(0, 8) + '...' : name;
                }
            },
            series: [{
                name: '学历分布',
                type: 'pie',
                radius: ['45%', '70%'],
                center: ['50%', '45%'],
                avoidLabelOverlap: true,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: true,
                    position: 'outside',
                    formatter: '{b}：{d}%',
                    fontSize: 12
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 14,
                        fontWeight: 'bold'
                    }
                },
                data: data.map(item => ({
                    name: item.name || '未填写',
                    value: item.value || 0
                }))
            }]
        };
        chart.setOption(option);
    }

    // 渲染职称分布饼图
    function renderTitleChart(data) {
        const chart = echarts.init(document.getElementById('titleChart'));
        const option = {
            title: {
                text: '职称分布',
                left: 'center',
                top: 20,
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'normal'
                }
            },
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c}人 ({d}%)'
            },
            legend: {
                orient: 'horizontal',
                left: 'center',
                bottom: 0,
                type: 'scroll',
                formatter: function(name) {
                    return name.length > 8 ? name.substring(0, 8) + '...' : name;
                }
            },
            series: [{
                name: '职称分布',
                type: 'pie',
                radius: ['45%', '70%'],
                center: ['50%', '45%'],
                avoidLabelOverlap: true,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: true,
                    position: 'outside',
                    formatter: '{b}：{d}%',
                    fontSize: 12
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 14,
                        fontWeight: 'bold'
                    }
                },
                data: data.map(item => ({
                    name: item.name || '未填写',
                    value: item.value || 0
                }))
            }]
        };
        chart.setOption(option);
    }

    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', function() {
        const charts = ['departmentChart', 'educationChart', 'titleChart']
            .map(id => echarts.getInstanceByDom(document.getElementById(id)))
            .filter(chart => chart);
        
        charts.forEach(chart => chart.resize());
    });


  // 生产计划进度统计
async function showPlanCompletionAnalysis(element) {
    try {
        document.getElementById('reportDropdown').textContent = element.textContent;
        document.getElementById('chartsArea').style.display = 'none';
        document.getElementById('personChartsArea').style.display = 'none';
        document.getElementById('planCompletionArea').style.display = 'block';

        // 使用固定数据而不是从后端获取
        const fixedData = {
            totalCompletionRate: 67, // 固定整体完成率为66%
            departmentCompletion: {
               '表面处理车间': 78,
                '锻压车间': 62,
                '组装车间': 55,
                '机加车间': 91,
                '质检车间': 67
            },
            employeeCompletion: {
                'J2023001': 95,
                'J2023002': 92,
                'J2023004': 89,
                'J2023005': 87,
                'J2023006': 85
            }
        };

        // 渲染整体完成率仪表盘
        renderPlanCompletionGauge(fixedData.totalCompletionRate);

        // 转换部门完成率数据格式
        const departmentData = Object.entries(fixedData.departmentCompletion).map(([name, value]) => ({
            name,
            value: parseFloat(value.toFixed(2))
        }));

        // 渲染部门完成率仪表盘组
        renderDepartmentGauges(departmentData);

        // 转换员工完成率数据格式并排序
        const employeeData = Object.entries(fixedData.employeeCompletion)
            .map(([jobNumber, value]) => ({
                name: jobNumber,
                value: parseFloat(value.toFixed(2))
            }))
            .sort((a, b) => b.value - a.value)
            .slice(0, 5); // 获取Top 5

        // 渲染Top 5高效员工条形图
        renderTopEmployeesChart(employeeData);
    } catch (error) {
        console.error('获取计划完成数据失败:', error);
        alert('获取计划完成数据失败，请稍后重试');
    }
}


    // 整体完成率仪表盘
    function renderPlanCompletionGauge(value) {
        const chart = echarts.init(document.getElementById('planCompletionGauge'));
        const option = {
            title: {
                text: '整体计划完成率',
                left: 'center',
                top: '5%',
                textStyle: { fontSize: 16, fontWeight: 'normal' }
            },
            tooltip: { formatter: '{a} <br/>{b} : {c}%' },
            series: [{
                name: '计划完成率',
                type: 'gauge',
                startAngle: 180,
                endAngle: 0,
                min: 0,
                max: 100,
                splitNumber: 10,
                radius: '80%',
                center: ['50%', '70%'],
                itemStyle: { color: '#58D9F9' },
                progress: { show: true, roundCap: true, width: 18 },
                pointer: { show: false },
                axisLine: { roundCap: true, lineStyle: { width: 18 } },
                axisTick: { distance: -23, splitNumber: 5, length: 8, lineStyle: { width: 1, color: '#999' } },
                splitLine: { distance: -23, length: 12, lineStyle: { width: 2, color: '#999' } },
                axisLabel: { distance: -25, color: '#999', fontSize: 12, formatter: v => (v === 0 || v === 100) ? '' : v },
                title: { offsetCenter: [0, '-15%'], fontSize: 14 },
                detail: { backgroundColor: 'transparent', borderWidth: 0, width: 60, height: 40, offsetCenter: [0, '30%'], valueAnimation: true, formatter: '{value}%', color: '#58D9F9', fontSize: 20, fontWeight: 'bold' },
                data: [{ value: value, name: '完成率' }]
            }]
        };
        chart.setOption(option);
    }

    // 各车间完成率仪表盘组
    function renderDepartmentGauges(departmentData) {
        const container = document.getElementById('departmentGauges');
        container.innerHTML = ''; // 清空容器
        container.style.display = 'flex';
        container.style.flexWrap = 'wrap';
        container.style.justifyContent = 'center';
        container.style.gap = '20px';

        departmentData.forEach((dept, index) => {
            const gaugeDiv = document.createElement('div');
            gaugeDiv.style.width = '300px';
            gaugeDiv.style.height = '300px';
            container.appendChild(gaugeDiv);

            const chart = echarts.init(gaugeDiv);
        const option = {
                title: {
                    text: dept.name + '完成率',
                    left: 'center',
                    top: '5%',
                    textStyle: { fontSize: 14, fontWeight: 'normal' }
                },
                tooltip: { formatter: '{a} <br/>{b} : {c}%' },
            series: [{
                name: '完成率',
                    type: 'gauge',
                    radius: '70%',
                    progress: { show: true },
                    detail: { valueAnimation: true, formatter: '{value}%', fontSize: 16 },
                    data: [{ value: dept.value, name: '完成率' }],
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: '#67e0e3' },
                            { offset: 1, color: '#37a2da' }
                        ])
                    }
                }]
            };
            chart.setOption(option);
        });
    }

    // Top N高效员工条形图
    function renderTopEmployeesChart(employeeData) {
        const chart = echarts.init(document.getElementById('topEmployeesChart'));
        const option = {
            title: {
                text: 'Top 5高效员工',
                left: 'center',
                top: '20px',
                textStyle: { fontSize: 16, fontWeight: 'normal' }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: { type: 'shadow' }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'value',
                name: '完成率(%)',
                max: 100
            },
            yAxis: {
                type: 'category',
                data: employeeData.map(item => item.name),
                axisLabel: { interval: 0 }
            },
            series: [{
                name: '完成率',
                type: 'bar',
                data: employeeData.map(item => item.value),
                label: {
                    show: true,
                    position: 'right',
                    formatter: '{c}%'
                },
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                        { offset: 0, color: '#83bff6' },
                        { offset: 0.5, color: '#5470C6' },
                        { offset: 1, color: '#2f4999' }
                    ])
                }
            }]
        };
        chart.setOption(option);
    }


    function showRepairAndScrapAnalysis(element) {
            // 更新下拉菜单文本
            document.getElementById('reportDropdown').textContent = element.textContent;

            // 隐藏其他报表区域
            document.getElementById('chartsArea').style.display = 'none';
            document.getElementById('personChartsArea').style.display = 'none';
            document.getElementById('planCompletionArea').style.display = 'none';

            // 显示保修和报废分析区域
            document.getElementById('repairAndScrapArea').style.display = 'block';

        // 并行获取设备、报修和报废数据
            Promise.all([
                axios.get('http://localhost:8080/api/devices'),
                axios.get('http://localhost:8080/api/device/repairs/getRepair'),
                axios.get('http://localhost:8080/api/device/scraps/getScrap')
            ]).then(([devicesRes, repairsRes, scrapsRes]) => {
            const devices = devicesRes.data;
                const repairs = repairsRes.data;
                const scraps = scrapsRes.data;

            // 计算设备报修率
            const totalDevices = devices.length;
                const approvedRepairs = repairs.filter(r => r.isApproved).length;
            const repairRate = totalDevices ? (approvedRepairs / totalDevices * 100).toFixed(1) : 0;

            // 计算设备报废率
                const approvedScraps = scraps.filter(s => s.isApproved).length;
            const scrapRate = totalDevices ? (approvedScraps / totalDevices * 100).toFixed(1) : 0;

            // 获取设备总数和报修报废数量
            const repairCount = repairs.length;
            const scrapCount = scraps.length;

                // 渲染图表
                renderRepairRateChart(parseFloat(repairRate));
                renderScrapRateChart(parseFloat(scrapRate));
            renderRepairSuccessRateChart(totalDevices, repairCount, scrapCount);
            }).catch(error => {
            console.error('获取设备报修和报废数据失败:', error);
            alert('获取数据失败，请稍后重试');
            });
    }

    function renderRepairRateChart(rate) {
        const chart = echarts.init(document.getElementById('repairRateChart'));
        const option = {
            title: {
                text: '设备报修率',
                left: 'center',
                top: '5%',
                textStyle: { fontSize: 16, fontWeight: 'normal' }
            },
            tooltip: { formatter: '{a} <br/>{b} : {c}%' },
            series: [{
                name: '报修率',
                type: 'gauge',
                startAngle: 180,
                endAngle: 0,
                min: 0,
                max: 100,
                splitNumber: 10,
                radius: '80%',
                center: ['50%', '70%'],
                itemStyle: { color: '#67e0e3' },
                progress: { show: true, roundCap: true, width: 18 },
                pointer: { show: false },
                axisLine: { roundCap: true, lineStyle: { width: 18 } },
                axisTick: { distance: -23, splitNumber: 5, length: 8, lineStyle: { width: 1, color: '#999' } },
                splitLine: { distance: -23, length: 12, lineStyle: { width: 2, color: '#999' } },
                axisLabel: { distance: -25, color: '#999', fontSize: 12 },
                title: { offsetCenter: [0, '-15%'], fontSize: 14 },
                detail: {
                    backgroundColor: 'transparent',
                    borderWidth: 0,
                    width: 60,
                    height: 40,
                    offsetCenter: [0, '30%'],
                    valueAnimation: true,
                    formatter: '{value}%',
                    color: '#67e0e3',
                    fontSize: 20,
                    fontWeight: 'bold'
                },
                data: [{ value: rate, name: '报修率' }]
            }]
        };
        chart.setOption(option);
    }

    function renderScrapRateChart(rate) {
        const chart = echarts.init(document.getElementById('scrapRateChart'));
        const option = {
            title: {
                text: '设备报废率',
                left: 'center',
                top: '5%',
                textStyle: { fontSize: 16, fontWeight: 'normal' }
            },
            tooltip: { formatter: '{a} <br/>{b} : {c}%' },
            series: [{
                name: '报废率',
                type: 'gauge',
                startAngle: 180,
                endAngle: 0,
                min: 0,
                max: 100,
                splitNumber: 10,
                radius: '80%',
                center: ['50%', '70%'],
                itemStyle: { color: '#ff6e76' },
                progress: { show: true, roundCap: true, width: 18 },
                pointer: { show: false },
                axisLine: { roundCap: true, lineStyle: { width: 18 } },
                axisTick: { distance: -23, splitNumber: 5, length: 8, lineStyle: { width: 1, color: '#999' } },
                splitLine: { distance: -23, length: 12, lineStyle: { width: 2, color: '#999' } },
                axisLabel: { distance: -25, color: '#999', fontSize: 12 },
                title: { offsetCenter: [0, '-15%'], fontSize: 14 },
                detail: {
                    backgroundColor: 'transparent',
                    borderWidth: 0,
                    width: 60,
                    height: 40,
                    offsetCenter: [0, '30%'],
                    valueAnimation: true,
                    formatter: '{value}%',
                    color: '#ff6e76',
                    fontSize: 20,
                    fontWeight: 'bold'
                },
                data: [{ value: rate, name: '报废率' }]
            }]
        };
        chart.setOption(option);
    }

    function renderRepairSuccessRateChart(totalDevices, repairCount, scrapCount) {
        const chart = echarts.init(document.getElementById('repairSuccessRateChart'));
        const option = {
            title: {
                text: '设备状态统计',
                left: 'center',
                top: '20px',
                textStyle: { fontSize: 16, fontWeight: 'normal' }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: { type: 'shadow' },
                formatter: '{b}: {c}台'
            },
            legend: {
                data: ['设备总数', '报修数量', '报废数量'],
                top: '50px'
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                top: '25%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: ['设备状态'],
                axisLabel: { interval: 0, fontSize: 12, color: '#666' },
                axisTick: { alignWithLabel: true }
            },
            yAxis: {
                type: 'value',
                name: '数量',
                minInterval: 1,
                splitLine: { lineStyle: { type: 'dashed' } },
                axisLabel: { formatter: '{value}台' }
            },
            series: [{
                name: '设备总数',
                type: 'bar',
                barWidth: '20%',
                data: [totalDevices],
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#91cc75' },
                        { offset: 1, color: '#5eb95e' }
                    ]),
                    borderRadius: [5, 5, 0, 0]
                },
                label: {
                    show: true,
                    position: 'top',
                    formatter: '{c}台',
                    fontSize: 12
                }
            }, {
                name: '报修数量',
                            type: 'bar',
                barWidth: '20%',
                data: [repairCount],
                            itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#83bff6' },
                        { offset: 1, color: '#5470C6' }
                    ]),
                                borderRadius: [5, 5, 0, 0]
                            },
                            label: {
                                show: true,
                                position: 'top',
                    formatter: '{c}台',
                    fontSize: 12
                }
            }, {
                name: '报废数量',
                type: 'bar',
                barWidth: '20%',
                data: [scrapCount],
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#ff9897' },
                        { offset: 1, color: '#ff6e76' }
                    ]),
                    borderRadius: [5, 5, 0, 0]
                },
                label: {
                    show: true,
                    position: 'top',
                    formatter: '{c}台',
                    fontSize: 12
                }
            }]
        };
        chart.setOption(option);
    }


    // 显示设备报修详情的模态框
    function showRepairDetail(repair) {
        // 设置报修详情信息
        document.getElementById('modal-repair-id').textContent = repair.repairId;
        document.getElementById('modal-device-number').textContent = repair.deviceNumber || '未提供';
        document.getElementById('modal-device-name').textContent = repair.deviceName || '未提供';
        document.getElementById('modal-repair-desc').textContent = repair.repairDesc || repair.description || '未提供';
        document.getElementById('modal-applicant-name').textContent = repair.applicantName || repair.applicantJobNumber || '未提供';

        // 重置表单
        document.getElementById('repairApprovalStatus').value = '';
        document.getElementById('repairReviewDescription').value = '';

        // 绑定提交按钮事件
        const submitBtn = document.getElementById('submitRepairReviewBtn');
        submitBtn.onclick = () => submitRepairReview(repair.repairId);

        // 绑定暂不处理按钮事件
        const tempHoldBtn = document.getElementById('repairTempHoldBtn');
        tempHoldBtn.onclick = () => {
            const modal = bootstrap.Modal.getInstance(document.getElementById('repairReviewModal'));
            if (modal) modal.hide();
        };

        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('repairReviewModal'));
        modal.show();
    }

    // 提交设备报修审核意见
    async function submitRepairReview(repairId) {
        try {
            // 验证表单
            const approvalStatus = document.getElementById('repairApprovalStatus').value;
            const reviewDesc = document.getElementById('repairReviewDescription').value.trim();
            
            if (!approvalStatus) {
                alert('请选择处理意见');
                return;
            }
            
            if (!reviewDesc) {
                alert('请输入审核意见');
                return;
            }
            
            // 获取当前用户信息
            const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
            

            const isApproved = approvalStatus === 'true';

            // 构建审核数据
            const reviewData = {
                repairId: repairId,
                isApproved: isApproved,
                reviewDesc: reviewDesc,
                applicantJobNumber: userInfo.jobNumber
            };
            
            // 发送审核请求
            const response = await axios.put('http://localhost:8080/api/device/repairs/review', reviewData, {
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (response.status === 200 || response.status === 201) {
                alert('报修审核已提交！');
                
                // 关闭模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('repairReviewModal'));
                if (modal) modal.hide();
                
                // 刷新消息列表
                fetchUnapprovedApplicationsAndComplaints();
            } else {
                throw new Error('服务器响应异常');
            }
        } catch (error) {
            console.error('提交报修审核时出错:', error);
            alert('提交报修审核失败！');
        }
    }

    // 显示设备报废详情的模态框
    function showScrapDetail(scrap) {
        // 设置报废详情信息
        document.getElementById('modal-scrap-id').textContent = scrap.scrapId;
        document.getElementById('modal-scrap-device-number').textContent = scrap.deviceNumber || '未提供';
        document.getElementById('modal-scrap-device-name').textContent = scrap.deviceName || '未提供';
        document.getElementById('modal-scrap-desc').textContent = scrap.description || '未提供';
        document.getElementById('modal-scrap-applicant').textContent = scrap.applicantName || scrap.applicantJobNumber || '未提供';

        // 重置表单
        document.getElementById('scrapApprovalStatus').value = '';
        document.getElementById('scrapReviewDescription').value = '';

        // 绑定提交按钮事件
        const submitBtn = document.getElementById('submitScrapReviewBtn');
        submitBtn.onclick = () => submitScrapReview(scrap.scrapId);

        // 绑定暂不处理按钮事件
        const tempHoldBtn = document.getElementById('scrapTempHoldBtn');
        tempHoldBtn.onclick = () => {
            const modal = bootstrap.Modal.getInstance(document.getElementById('scrapReviewModal'));
            if (modal) modal.hide();
        };

        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('scrapReviewModal'));
        modal.show();
    }

    // 提交设备报废审核意见
    async function submitScrapReview(scrapId) {
        try {
            // 验证表单
            const approvalStatus = document.getElementById('scrapApprovalStatus').value;
            const reviewDesc = document.getElementById('scrapReviewDescription').value.trim();
            
            if (!approvalStatus) {
                alert('请选择处理意见');
                return;
            }
            
            if (!reviewDesc) {
                alert('请输入审核意见');
                return;
            }
            
            // 获取当前用户信息
            const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
            

            const isApproved = approvalStatus === 'true';

            // 构建审核数据
            const reviewData = {
                scrapId: scrapId,
                isApproved: isApproved,
                description: reviewDesc,
                applicantJobNumber: userInfo.jobNumber
            };
            
            // 发送审核请求
            const response = await axios.put('http://localhost:8080/api/device/scraps/review', reviewData, {
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (response.status === 200 || response.status === 201) {
                alert('报废审核已提交！');
                
                // 关闭模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('scrapReviewModal'));
                if (modal) modal.hide();
                
                // 刷新消息列表
                fetchUnapprovedApplicationsAndComplaints();
            } else {
                throw new Error('服务器响应异常');
            }
        } catch (error) {
            console.error('提交报废审核时出错:', error);
            alert('提交报废审核失败！');
        }
    }

    
    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', function() {
        const charts = [
            'approvalRateChart', 'complaintRateChart', 'topComplaintsChart',
            'departmentChart', 'educationChart', 'titleChart',
            'planCompletionGauge', 'planCompletionWaterfall'
        ].map(id => echarts.getInstanceByDom(document.getElementById(id))).filter(chart => chart);
        charts.forEach(chart => chart.resize());
    });

</script>
</body>

    <!-- 产品申请详情模态框 -->
    <div class="modal fade ios-style" id="productApplicationDetailModal" tabindex="-1" aria-labelledby="productApplicationDetailModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="productApplicationDetailModalLabel">产品申请详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="product-submission-id" value="">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="detail-item">
                                <p><strong>申请ID:</strong> <span id="modal-product-submission-id"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>计划ID:</strong> <span id="modal-product-plan-id"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>提交人工作编号:</strong> <span id="modal-product-submitter"></span></p>
                            </div>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-12">
                            <label class="form-label">申请描述:</label>
                            <textarea class="form-control" id="modal-product-description" rows="2" readonly></textarea>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-12">
                            <h6>申请产品明细</h6>
                            <table class="table table-bordered">
                                <thead>
                                <tr>
                                    <th>产品编码</th>
                                    <th>申请数量</th>
                                </tr>
                                </thead>
                                <tbody id="modal-product-details-body">
                                <!-- 产品明细将通过JavaScript动态填充 -->
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-12">
                            <label for="modal-product-review-comment" class="form-label">审核意见:</label>
                            <textarea class="form-control" id="modal-product-review-comment" rows="3"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-success" onclick="rejectProductApplication()">拒绝</button>
                    <button type="button" class="btn btn-primary" onclick="approveProductApplication()">批准</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 供应商申请详情模态框 -->
    <div class="modal fade ios-style" id="applicationDetailModal" tabindex="-1" aria-labelledby="applicationDetailModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="applicationDetailModalLabel">供应商申请详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="detail-item">
                                <p><strong>申请ID:</strong> <span id="modal-application-id"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>供应商名称:</strong> <span id="modal-provider-name"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>工厂地址:</strong> <span id="modal-factory-address"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>负责人姓名:</strong> <span id="modal-manager-name"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>负责人电话:</strong> <span id="modal-manager-phone"></span></p>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="detail-item">
                                <p><strong>公司类型:</strong> <span id="modal-company-type"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>注册资本:</strong> <span id="modal-registered-capital"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>员工人数:</strong> <span id="modal-employee-count"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>成立年份:</strong> <span id="modal-established-year"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>申请人工作编号:</strong> <span id="modal-applicant-job-number"></span></p>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="detail-item">
                                <p><strong>公司简介:</strong> <span id="modal-profile"></span></p>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <form id="reviewForm">
                                <div class="mb-3">
                                    <label for="approvalStatus" class="form-label">处理意见: <span class="text-danger">*</span></label>
                                    <select class="form-select" id="approvalStatus" required>
                                        <option value="" selected disabled>请选择处理意见</option>
                                        <option value="true">审批通过</option>
                                        <option value="false">拒绝申请</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label for="description" class="form-label">审核意见: <span class="text-danger">*</span></label>
                                    <textarea class="form-control" id="description" rows="3" required></textarea>
                                </div>
                                <div class="mb-3">
                                    <label for="initialRating" class="form-label">初始评分: <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="initialRating" min="0" max="5" required>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" id="temp-hold-btn">暂不处理</button>
                    <button type="button" class="btn btn-success" id="submit-review-btn">提交审批</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 供应商投诉审核模态框 -->
    <div class="modal fade ios-style" id="complaintReviewModal" tabindex="-1" aria-labelledby="complaintReviewModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="complaintReviewModalLabel">供应商投诉审核</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="detail-item">
                                <p><strong>投诉ID:</strong> <span id="modal-complaint-id"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>供应商名称:</strong> <span id="modal-complaint-provider-name"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>问题材料:</strong> <span id="modal-complaint-material"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>投诉描述:</strong> <span id="modal-complaint-description"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>投诉人工作编号:</strong> <span id="modal-complaint-job-number"></span></p>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <form id="complaintReviewForm">
                                <div class="mb-3">
                                    <label for="complaintApprovalStatus" class="form-label">处理意见: <span class="text-danger">*</span></label>
                                    <select class="form-select" id="complaintApprovalStatus" required>
                                        <option value="" selected disabled>请选择处理意见</option>
                                        <option value="true">审核通过</option>
                                        <option value="false">拒绝投诉</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label for="complaintReviewDescription" class="form-label">审核意见: <span class="text-danger">*</span></label>
                                    <textarea class="form-control" id="complaintReviewDescription" rows="3" required></textarea>
                                </div>
                                <div class="mb-3">
                                    <label for="ratingDeduction" class="form-label">供应商评级扣分: <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="ratingDeduction" min="0" max="5" required>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" id="complaintTempHoldBtn">暂不处理</button>
                    <button type="button" class="btn btn-success" id="submitComplaintReviewBtn">提交审核</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 设备报修审核模态框 -->
    <div class="modal fade ios-style" id="repairReviewModal" tabindex="-1" aria-labelledby="repairReviewModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="repairReviewModalLabel">设备报修审核</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="detail-item">
                                <p><strong>报修ID:</strong> <span id="modal-repair-id"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>设备编号:</strong> <span id="modal-device-number"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>设备名称:</strong> <span id="modal-device-name"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>报修描述:</strong> <span id="modal-repair-desc"></span></p>
                            </div>
                            <div class="detail-item">
                                <p><strong>申请人:</strong> <span id="modal-applicant-name"></span></p>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <form id="repairReviewForm">
                                <div class="mb-3">
                                    <label for="repairApprovalStatus" class="form-label">处理意见: <span class="text-danger">*</span></label>
                                    <select class="form-select" id="repairApprovalStatus" required>
                                        <option value="" selected disabled>请选择处理意见</option>
                                        <option value="true">审核通过</option>
                                        <option value="false">拒绝报修</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label for="repairReviewDescription" class="form-label">审核意见: <span class="text-danger">*</span></label>
                                    <textarea class="form-control" id="repairReviewDescription" rows="3" required></textarea>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" id="repairTempHoldBtn">暂不处理</button>
                    <button type="button" class="btn btn-success" id="submitRepairReviewBtn">提交审核</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 设备报废审核详情弹窗 -->
    <div class="modal fade ios-style" id="scrapReviewModal" tabindex="-1" aria-labelledby="scrapReviewModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="scrapReviewModalLabel">设备报废审核</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="detail-item">
                        <p><strong>报废ID:</strong> <span id="modal-scrap-id"></span></p>
                        <p><strong>设备编号:</strong> <span id="modal-scrap-device-number"></span></p>
                        <p><strong>设备名称:</strong> <span id="modal-scrap-device-name"></span></p>
                        <p><strong>报废描述:</strong> <span id="modal-scrap-desc"></span></p>
                        <p><strong>申请人:</strong> <span id="modal-scrap-applicant"></span></p>
                    </div>
                    <form id="scrapReviewForm">
                        <div class="mb-3">
                            <label for="scrapApprovalStatus" class="form-label">处理意见: <span class="text-danger">*</span></label>
                            <select class="form-select" id="scrapApprovalStatus" required>
                                <option value="" selected disabled>请选择处理意见</option>
                                <option value="true">审核通过</option>
                                <option value="false">拒绝报废</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="scrapReviewDescription" class="form-label">审核意见: <span class="text-danger">*</span></label>
                            <textarea class="form-control" id="scrapReviewDescription" rows="3" required></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" id="scrapTempHoldBtn">暂不处理</button>
                    <button type="button" class="btn btn-success" id="submitScrapReviewBtn">提交审核</button>
                </div>
            </div>
        </div>
    </div>

</html>